using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections;
using System.Runtime.InteropServices;

namespace Cataloger
{
  public class FileInfoManager
  {   
    #region private constants
    const int MAX_PATH = 256;
    const int NAMESIZE = 80;

    const uint SHGFI_ICON = 0x100;
    const uint SHGFI_SMALLICON = 0x1;
    const uint SHGFI_LARGEICON = 0x0; // 'Large icon
    const uint SHGFI_USEFILEATTRIBUTES = 0x10;
    const uint SHGFI_TYPENAME = 0x400;	
    const uint FILE_ATTRIBUTE_ARCHIVE = 0x20;
    const uint FILE_ATTRIBUTE_COMPRESSED = 0x800;
    const uint FILE_ATTRIBUTE_DIRECTORY = 0x10;
    const uint FILE_ATTRIBUTE_HIDDEN = 0x2;
    const uint FILE_ATTRIBUTE_NORMAL = 0x0;
    const uint FILE_ATTRIBUTE_READONLY = 0x1;
    const uint FILE_ATTRIBUTE_SYSTEM = 0x4;
   
    #endregion

    #region Internals
    [StructLayout(LayoutKind.Sequential)] 
      private struct SHFILEINFO
    { 
      public IntPtr hIcon; 
      public int iIcon; 
      public uint	dwAttributes; 
      [MarshalAs (UnmanagedType.ByValTStr, SizeConst=MAX_PATH) ] 
      public string szDisplayName; 
      [MarshalAs (UnmanagedType.ByValTStr, SizeConst=NAMESIZE)]
      public string szTypeName; 
    };

    [DllImport("Shell32.dll")]
    private static extern IntPtr SHGetFileInfo  (string pszPath,
      uint dwFileAttributes,
      ref SHFILEINFO psfi,
      uint cbFileInfo,
      uint uFlags);

    [DllImport("User32.dll")]
    public static extern int DestroyIcon (IntPtr hIcon);
    #endregion

    #region Public Methods
    public virtual Icon GetLargeFileTypeIcon (string pFileExtension)
    {
      SHFILEINFO psfi = new SHFILEINFO ();
      uint uFlags = SHGFI_ICON | SHGFI_LARGEICON | SHGFI_USEFILEATTRIBUTES;// SHGFI_SMALLICON tej flagi uzyc aby pobrac mala ikonke

      uint fileAttribute = FILE_ATTRIBUTE_ARCHIVE
        | FILE_ATTRIBUTE_COMPRESSED
        | FILE_ATTRIBUTE_HIDDEN
        | FILE_ATTRIBUTE_NORMAL
        | FILE_ATTRIBUTE_READONLY 
        | FILE_ATTRIBUTE_SYSTEM;

      SHGetFileInfo (pFileExtension, fileAttribute, ref psfi, 
        (uint) Marshal.SizeOf (psfi), uFlags);

     

      Icon icon = (Icon) Icon.FromHandle(psfi.hIcon).Clone(); 
      DestroyIcon(psfi.hIcon);
      return icon;
    }

    public virtual string GetFileTypeName(string pFileExtension)
    {
      SHFILEINFO psfi = new SHFILEINFO ();
      uint uFlags = SHGFI_TYPENAME | SHGFI_USEFILEATTRIBUTES;

      uint fileAttribute = FILE_ATTRIBUTE_ARCHIVE
        | FILE_ATTRIBUTE_COMPRESSED
        | FILE_ATTRIBUTE_HIDDEN
        | FILE_ATTRIBUTE_NORMAL
        | FILE_ATTRIBUTE_READONLY 
        | FILE_ATTRIBUTE_SYSTEM;

      psfi.szTypeName = new string(' ', NAMESIZE);
  

      SHGetFileInfo (pFileExtension, fileAttribute, ref psfi,
        (uint) Marshal.SizeOf (psfi), uFlags);
			
      return psfi.szTypeName;
    }
    #endregion
  }
}
